<template>
  <view>
    <view class="sticky top-0 z-[10] backdrop-blur-sm">
      <!-- 导航栏 -->
      <up-navbar
        title="赏袋"
        leftIcon=""
        :placeholder="true"
        bgColor="transparent"
        leftIconColor="#fff"
        titleStyle="color: #fff;font-weight: bold;font-size: 34rpx">
      </up-navbar>
      <!-- 分类 -->
      <view class="flex items-center justify-between pr-[20rpx]">
        <view class="flex-1">
          <TabsView
            :list="classfyList"
            @classfyChange="classfyChange"></TabsView>
        </view>
        <view class="w-[108rpx] h-[56rpx]" @click="utils.goRules('发货规则')">
          <up-image
            :src="rules"
            width="100%"
            height="100%"
            bgColor="transparent"></up-image>
        </view>
      </view>
      <!-- 标签 -->
      <view class="flex items-center justify-between pr-[20rpx]">
        <view>
          <up-image
            :src="tag"
            width="140rpx"
            height="50rpx"
            bgColor="transparent"></up-image>
        </view>
        <view @click="sortClick">
          <up-image
            :src="params.orderType == 1 ? price_desc : price_asc"
            width="108rpx"
            height="40rpx"
            bgColor="transparent"></up-image>
        </view>
      </view>
    </view>
    <!-- 商品列表 -->
    <view
      v-if="giftList.length"
      class="grid grid-cols-3 gap-[20rpx] px-[20rpx] mt-[30rpx] animate__HeightIn"
      :style="{
        animationDuration: Math.ceil(giftList.length / 3) * 1.2 + 's',
      }">
      <view v-for="item in giftList" :key="item.id">
        <view
          class="w-[224rpx] h-[224rpx] flex items-center justify-center relative">
          <!-- 边框 -->
          <up-image
            :src="goods_mask"
            class="absolute top-0 left-0 z-[1]"
            width="224rpx"
            height="224rpx"
            bgColor="transparent"></up-image>
          <!-- end -->
          <!-- 商品 -->
          <view class="w-[208rpx] h-[208rpx]">
            <up-image
              :src="$url(item.appGood?.pic)"
              width="208rpx"
              height="208rpx"
              bgColor="#000"></up-image>
          </view>
          <!-- end -->
          <view
            class="absolute top-[8rpx] right-[8rpx] z-[2]"
            v-if="params.type !== 3">
            <CheckBox v-model="item.check" />
          </view>
        </view>
        <view class="text-white text-[24rpx] p-[8rpx] leading-[30rpx]">
          <view class="line-clamp-1">{{ item.appGood?.name }}</view>
          <view v-if="params.type !== 3"
            >参考价: {{ Number(item.appGood?.demoPrice).toFixed(2) }}</view
          >
          <view v-else
            >转换代币: {{ Number(item.appGood?.demoPrice).toFixed(2) }}</view
          >
          <view>数量: {{ item.num }}</view>
        </view>
      </view>
    </view>
    <up-empty v-else mode="list" marginTop="200rpx" />
    <!-- 操作栏 -->
    <view
      v-if="params.type !== 3"
      class="fixed z-20 h-[136rpx] w-full px-[20rpx] bg-[#000] flex item-center justify-between options">
      <view class="font-heiti text-white h-full flex flex-col justify-center">
        <view class="flex items-center">
          <!-- 选中 -->
          <CheckBox v-model="isAllChecked" />
          <!-- end -->
          <view class="text-[32rpx] ml-[4rpx]">全选</view>
        </view>
        <view class="text-[28rpx]">已选{{ checkNum }}件</view>
      </view>
      <view class="flex items-center gap-[20rpx]">
        <MyButton
          text="一键发货"
          @click="giftShipments"
          v-if="params.type === 1" />
        <MyButton
          text="转换代币"
          v-if="params.type === 1"
          @click="convertNow" />
        <MyButton :text="safeCabinetText" @click="safeCabinet" />
      </view>
    </view>
    <!-- 占位元素 -->
    <view class="h-[136rpx]"></view>
    <!-- 背景 -->
    <BackgroundImage />
    <!-- 底部导航栏 -->
    <CustomTabbar :currentIndex="2" />
    <!-- 发货规则 -->
    <MyPopup
      :show="shipmentsShow"
      :titleIcon="deliver"
      @close="shipmentsShow = false">
      <view class="w-[622rpx] p-[40rpx] flex flex-col items-center">
        <scroll-view scroll-y class="h-[540rpx] mb-[24rpx]">
          <rich-text
            class="text-white text-[30rpx]"
            nodes="我知道了"></rich-text>
        </scroll-view>
        <MyButton text="我知道了" @click="shipmentsShow = false" />
      </view>
    </MyPopup>
    <!-- 转换 -->
    <MyPopup :titleIcon="changeTitle" :show="exchangeShow">
      <view
        class="w-[622rpx] font-heiti text-white px-[48rpx] pt-[16rpx] pb-[40rpx] flex flex-col items-center justify-center">
        <view class="text-[44rpx]"
          >确定将{{ exchangeListTotal }}个赏品转换</view
        >
        <view class="text-[28rpx]"
          >消耗赏品价值: ￥{{ exchangeGoodsvalue.toFixed(2) }}</view
        >
        <view class="text-[28rpx]"
          >转换代币: {{ exchangeGoodsvalue.toFixed(2) }}</view
        >
        <view
          v-if="exchangeList.length <= 1"
          class="flex flex-col items-center mt-[16rpx] w-full py-[32rpx] border-[4rpx] border-[#8B8B8B] rounded-[24rpx] text-[22rpx]">
          <view
            class="flex flex-col items-center"
            v-for="item in exchangeList"
            :key="item.id">
            <view
              class="w-[168rpx] h-[168rpx] flex items-center justify-center relative">
              <up-image
                class="absolute top-0 left-0 z-10"
                :src="goods_mask"
                width="100%"
                height="100%"
                bgColor="transparent"></up-image>
              <up-image
                :src="$url(item.appGood.pic)"
                width="156rpx"
                height="156rpx"
                bgColor="transparent"></up-image>
            </view>
            <view class="line-clamp-1 max-w-[168rpx]">{{
              item.appGood.name
            }}</view>
            <view>参考价: {{ item.appGood.demoPrice.toFixed(2) }}</view>
          </view>
          <view class="w-[74rpx] h-[74rpx] my-[24rpx]">
            <up-image
              :src="arrow_down"
              width="100%"
              height="100%"
              bgColor="transparent"></up-image>
          </view>
          <view class="flex flex-col items-center">
            <view
              class="w-[168rpx] h-[168rpx] flex items-center justify-center relative">
              <up-image
                class="absolute top-0 left-0"
                :src="goods_mask"
                width="100%"
                height="100%"
                bgColor="transparent"></up-image>
              <up-image
                :src="coin"
                width="104rpx"
                height="104rpx"
                bgColor="transparent"></up-image>
            </view>
            <view class="line-clamp-1 max-w-[168rpx]">代币</view>
            <view>数量: {{ exchangeGoodsvalue.toFixed(2) }}</view>
          </view>
        </view>
        <view
          v-else
          class="grid grid-cols-3 gap-x-[24rpx] gap-y-[16rpx] mt-[16rpx] w-full p-[24rpx] border-[4rpx] border-[#8B8B8B] rounded-[24rpx] text-[22rpx]">
          <view
            class="flex flex-col items-center justify-center"
            v-for="item in exchangeList"
            :key="item.id">
            <view
              class="w-[144rpx] h-[144rpx] flex items-center justify-center relative">
              <up-image
                class="absolute top-0 left-0 z-10"
                :src="goods_mask"
                width="100%"
                height="100%"
                bgColor="transparent"></up-image>
              <up-image
                :src="$url(item.appGood.pic)"
                width="132rpx"
                height="132rpx"
                bgColor="transparent"></up-image>
            </view>
            <view>
              <view
                class="line-clamp-1 max-w-[144rpx]"
                style="font-family: initial"
                >{{ item.appGood.name }}</view
              >
              <view
                class="line-clamp-1 max-w-[144rpx]"
                style="font-family: initial"
                >参考价: {{ item.appGood.demoPrice.toFixed(2) }}</view
              >
            </view>
          </view>
          <view
            class="flex flex-col items-center justify-center opacity-0"
            v-for="item in 6 - exchangeList.length"
            :key="item">
            <view
              class="w-[144rpx] h-[144rpx] flex items-center justify-center relative">
              <up-image
                class="absolute top-0 left-0 z-10"
                :src="goods_mask"
                width="100%"
                height="100%"
                bgColor="transparent"></up-image>
              <up-image
                src=""
                width="132rpx"
                height="132rpx"
                bgColor="transparent"></up-image>
            </view>
            <view>
              <view
                class="line-clamp-1 max-w-[144rpx]"
                style="font-family: initial"
                >XXX</view
              >
              <view
                class="line-clamp-1 max-w-[144rpx]"
                style="font-family: initial"
                >参考价: XXX</view
              >
            </view>
          </view>
          <view class="flex items-center justify-center">
            <view class="w-[74rpx] h-[74rpx] -rotate-90">
              <up-image
                :src="arrow_down"
                width="100%"
                height="100%"
                bgColor="transparent"></up-image>
            </view>
          </view>
          <view
            class="w-[144rpx] h-[144rpx] flex items-center justify-center relative">
            <up-image
              class="absolute top-0 left-0"
              :src="goods_mask"
              width="100%"
              height="100%"
              bgColor="transparent"></up-image>
            <up-image
              :src="coin"
              width="104rpx"
              height="104rpx"
              bgColor="transparent"></up-image>
          </view>
          <view class="flex items-center justify-center">
            <view>
              <view class="line-clamp-1 max-w-[168rpx]">代币:</view>
              <view>{{ exchangeGoodsvalue.toFixed(2) }}</view>
            </view>
          </view>
        </view>
        <view class="text-[20rpx] mt-[24rpx]">
          <view>请注意:</view>
          <view>
            <rich-text :nodes="exchangeRuleStr"></rich-text>
          </view>
        </view>
        <view class="flex justify-center items-center mt-[40rpx]">
          <view class="mr-[30rpx] grayscale">
            <MyButton text="取消" @click="exchangeShow = false"
          /></view>
          <view> <MyButton text="确定" @click="exchangeCoins" /></view>
        </view>
      </view>
    </MyPopup>
    <!-- 存保险柜 -->
    <CustomPopup
      :show="rmShow"
      :title="safeCabinetText"
      @close="rmShow = false">
      <view>
        <scroll-view scroll-y class="h-[700rpx]">
          <view class="px-[24rpx] flex flex-col gap-[24rpx]">
            <view
              v-for="item in safeCabinetList"
              :key="item.id"
              class="p-[20rpx] relative flex items-center rounded-[16rpx] border border-[#B51A26] gradient">
              <view
                class="w-[168rpx] h-[168rpx] flex items-center justify-center flex-shrink-0 relative">
                <up-image
                  :src="goods_mask"
                  width="100%"
                  height="100%"
                  class="absolute z-10 top-0 left-0"
                  bgColor="transparent" />
                <up-image
                  :src="$url(item.appGood.pic)"
                  width="156rpx"
                  height="156rpx"
                  bgColor="transparent" />
              </view>
              <view
                class="text-white text-[26rpx] h-[168rpx] flex flex-col justify-between flex-1 ml-[20rpx]">
                <view class="text-[32rpx] max-w-[10em] line-clamp-1">{{
                  item.appGood.name
                }}</view>
                <view>
                  <view>售价: {{ item.appGood.demoPrice }}元</view>
                  <view class="mt-[8rpx] flex items-center justify-between">
                    <view>总数量: {{ item.num }}个</view>
                    <up-number-box v-model="item.num" :max="item.checkNum">
                      <template #minus>
                        <up-icon
                          name="minus-circle"
                          color="#EECEA8"
                          size="32rpx"></up-icon>
                      </template>
                      <template #input>
                        <view
                          class="px-[16rpx] box-content text-center"
                          :style="{
                            width: item.num.toString().length + 'em',
                          }">
                          {{ item.num }}
                        </view>
                      </template>
                      <template #plus>
                        <up-icon
                          name="plus-circle"
                          color="#EECEA8"
                          size="32rpx"></up-icon>
                      </template>
                    </up-number-box>
                  </view>
                </view>
              </view>
              <up-icon
                @click="deleteGoods(item)"
                v-if="safeCabinetList.length > 1"
                class="absolute top-[24rpx] right-[24rpx]"
                name="trash"
                color="#fff"
                size="32rpx"></up-icon>
            </view>
          </view>
        </scroll-view>
        <view class="p-[40rpx] flex items-center justify-between">
          <view class="font-heiti text-white text-[40rpx]"
            >已选{{ checkListTotal }}件</view
          >
          <MyButton
            :text="safeCabinetText"
            @click="comfirmSafeCabinet"></MyButton>
        </view>
      </view>
    </CustomPopup>
    <!-- 转换 -->
    <CustomPopup :show="editShow" title="立即转换" @close="editShow = false">
      <view>
        <scroll-view scroll-y class="h-[700rpx]">
          <view class="px-[24rpx] flex flex-col gap-[24rpx]">
            <view
              v-for="item in exchangeList"
              :key="item.id"
              class="p-[20rpx] relative flex items-center rounded-[16rpx] border border-[#B51A26] gradient">
              <view
                class="w-[168rpx] h-[168rpx] flex items-center justify-center flex-shrink-0 relative">
                <up-image
                  :src="goods_mask"
                  width="168rpx"
                  height="168rpx"
                  class="absolute z-10 top-0 left-0"
                  bgColor="transparent" />
                <up-image
                  :src="$url(item.appGood.pic)"
                  width="156rpx"
                  height="156rpx"
                  bgColor="transparent" />
              </view>
              <view
                class="text-white text-[26rpx] h-[168rpx] flex flex-col justify-between flex-1 ml-[20rpx]">
                <view class="text-[32rpx] max-w-[10em] line-clamp-1">{{
                  item.appGood.name
                }}</view>
                <view>
                  <view>售价: {{ item.appGood.demoPrice }}元</view>
                  <view class="mt-[8rpx] flex items-center justify-between">
                    <view>总数量: {{ item.num }}个</view>
                    <up-number-box v-model="item.num" :max="item.checkNum">
                      <template #minus>
                        <up-icon
                          name="minus-circle"
                          color="#EECEA8"
                          size="32rpx"></up-icon>
                      </template>
                      <template #input>
                        <view
                          class="px-[16rpx] box-content text-center"
                          :style="{
                            width: item.num.toString().length + 'em',
                          }">
                          {{ item.num }}
                        </view>
                      </template>
                      <template #plus>
                        <up-icon
                          name="plus-circle"
                          color="#EECEA8"
                          size="32rpx"></up-icon>
                      </template>
                    </up-number-box>
                  </view>
                </view>
              </view>
              <up-icon
                @click="deleteExchangeGoods(item)"
                v-if="exchangeList.length > 1"
                class="absolute top-[24rpx] right-[24rpx]"
                name="trash"
                color="#fff"
                size="32rpx"></up-icon>
            </view>
          </view>
        </scroll-view>
        <view class="p-[40rpx] flex items-center justify-between">
          <view class="font-heiti text-white text-[40rpx]"
            >已选{{ exchangeListTotal }}件</view
          >
          <MyButton
            text="立即转换"
            @click="(exchangeShow = true), (editShow = false)"></MyButton>
        </view>
      </view>
    </CustomPopup>
  </view>
</template>

<script setup>
import { ref, reactive, watch, computed } from "vue";
import MyButton from "@/components/MyButton.vue";
import tag from "@/static/images/gift/tag.png";
import rules from "@/static/images/gift/rules.png";
import arrow_down from "@/static/images/gift/arrow_down.png";
import changeTitle from "@/static/images/gift/changeTitle.png";
import price_asc from "@/static/images/gift/price_desc.png";
import price_desc from "@/static/images/gift/price_asc.png";
import goods_mask from "@/static/images/gift/goods_mask.png";
import deliver from "@/static/images/gift/deliver.png";
import coin from "@/static/images/mine/coin.png";
import useClassfy from "@/hooks/useClassfy.js";
import { exchangeCoin, exchangeRule, getGiftList, moveBox } from "@/api/gift";
import { onShow } from "@dcloudio/uni-app";
import utils from "@/utils/utils";
import { useCheckoutStore } from "@/store/checkout";
import CustomPopup from "@/components/CustomPopup.vue";
onShow(() => {
  getGiftListReq();
});
const { classfyList, currentIndex, classfyChange } = useClassfy([
  {
    name: "赏袋",
    type: 1,
  },
  {
    name: "保险柜",
    type: 2,
  },
  {
    name: "已转换",
    type: 3,
  },
]); // 分类
const {
  giftList,
  getGiftListReq,
  params,
  isAllChecked,
  checkNum,
  giftShipments,
  safeCabinetList,
  checkListTotal,
  rmShow,
  safeCabinetText,
  safeCabinet,
  comfirmSafeCabinet,
  sortClick,
} = useGift(); // 赏品
const {
  exchangeList,
  exchangeListTotal,
  editShow,
  exchangeShow,
  convertNow,
  deleteExchangeGoods,
  deleteGoods,
  exchangeGoodsvalue,
  exchangeCoins,
  exchangeRules,
  exchangeRuleStr,
} = useExchange(); // 转换
const checkoutStore = useCheckoutStore();
const shipmentsShow = ref(false);

/**
 * @description 赏品
 * @returns {Object}
 * returns {Function} getGiftListReq 获取赏品列表
 * returns {Object} giftList 赏品列表
 * returns {Object} params 参数
 * returns {Boolean} isAllChecked 是否全选
 * returns {Number} checkNum 选中数量
 * returns {Object} giftShipments 赏品发货
 * returns {Object} safeCabinetList 选中赏品
 * returns {Boolean} rmShow 是否显示弹窗
 * returns {Function} safeCabinet 存保险柜
 */
function useGift() {
  const params = reactive({
    pageNum: 1,
    pageSize: 99999,
    total: 0,
    type: 1,
    orderType: 1,
    key: "",
  });
  const giftList = ref([]);
  const getGiftListReq = async () => {
    try {
      const res = await getGiftList(params);
      giftList.value = res.rows;
    } catch (error) {}
  };
  watch(currentIndex, () => {
    const type = classfyList.value[currentIndex.value].type;
    params.type = type;
    getGiftListReq();
  });
  const isAllChecked = computed({
    get() {
      return giftList.value.every((item) => item.check);
    },
    set(val) {
      giftList.value.forEach((item) => (item.check = val));
    },
  });
  const checkNum = computed(() => {
    return giftList.value
      .filter((item) => item.check)
      .reduce((total, item) => total + item.num, 0);
  });
  const giftShipments = () => {
    if (checkNum.value <= 0) return utils.showToast("请选择赏品");
    checkoutStore.checkoutParams.isSafe = params.type === 2;
    checkoutStore.checkoutParams.shipList = giftList.value
      .filter((item) => item.check)
      .map((item) => {
        return {
          goodId: item.goodId,
          num: item.num,
        };
      });
    utils.useRouter("/goods_packages/checkout/checkout");
  };
  const checkListTotal = computed(() => {
    return safeCabinetList.value.reduce((total, item) => total + item.num, 0);
  });
  const rmShow = ref(false);
  const safeCabinetList = ref([]);
  const safeCabinetText = computed(() => {
    return params.type === 1 ? "存保险柜" : "移出保险柜";
  });
  const safeCabinet = () => {
    if (checkNum.value <= 0) return utils.showToast("请选择赏品");
    safeCabinetList.value = giftList.value
      .filter((item) => item.check)
      .map((item) => {
        return {
          ...item,
          checkNum: item.num,
        };
      });
    rmShow.value = true;
  };
  const comfirmSafeCabinet = async () => {
    try {
      const res = await moveBox({
        list: safeCabinetList.value,
        isSafe: params.type === 2,
      });
      await getGiftListReq();
      utils.showToast("操作成功");
      rmShow.value = false;
    } catch (error) {}
  };
  const sortClick = () => {
    params.orderType = params.orderType === 1 ? 2 : 1;
    getGiftListReq();
  };
  return {
    giftList,
    getGiftListReq,
    params,
    isAllChecked,
    giftShipments,
    checkNum,
    safeCabinetList,
    checkListTotal,
    rmShow,
    safeCabinetText,
    safeCabinet,
    comfirmSafeCabinet,
    sortClick,
  };
}
/**
 * @description 转换
 */
function useExchange() {
  const exchangeShow = ref(false);
  const editShow = ref(false);
  const exchangeList = ref([]);
  const exchangeRuleStr = ref("");
  const deleteExchangeGoods = (item) => {
    exchangeList.value = exchangeList.value.filter((i) => i.id !== item.id);
  };
  const convertNow = () => {
    exchangeList.value = giftList.value
      .filter((item) => item.check)
      .map((item) => {
        return {
          ...item,
          checkNum: item.num,
        };
      });
    if (exchangeList.value.length <= 0) return utils.showToast("请选择赏品");
    if (exchangeList.value.length > 6)
      return utils.showToast("一次最多转换6种赏品");
    exchangeRules();
    editShow.value = true;
  };
  const exchangeListTotal = computed(() => {
    return exchangeList.value.reduce((total, item) => total + item.num, 0);
  });

  const exchangeGoodsvalue = computed(() => {
    return exchangeList.value.reduce(
      (total, item) => total + item.num * item.appGood.demoPrice,
      0
    );
  });
  const exchangeCoins = async () => {
    try {
      const res = await exchangeCoin({
        exchangeDtoList: exchangeList.value,
      });
      getGiftListReq();
      utils.showToast("兑换成功,请到我的钱包查看");
      exchangeShow.value = false;
    } catch (error) {}
  };
  const exchangeRules = async () => {
    try {
      const res = await exchangeRule();
      exchangeRuleStr.value = res.data.content;
    } catch (error) {}
  };
  return {
    exchangeList,
    exchangeShow,
    editShow,
    convertNow,
    deleteExchangeGoods,
    exchangeGoodsvalue,
    exchangeListTotal,
    exchangeCoins,
    exchangeRules,
    exchangeRuleStr,
  };
}
</script>

<style lang="scss" scoped>
.options {
  bottom: calc(constant(safe-area-inset-bottom) + 50px);
  bottom: calc(env(safe-area-inset-bottom) + 50px);
}
.animate__HeightIn {
  overflow: hidden;
  animation: HeightIn 1.2s linear;
}
@keyframes HeightIn {
  0% {
    height: auto;
    clip-path: inset(0 0 100% 0);
  }
  100% {
    height: auto;
    clip-path: inset(0);
  }
}
//渐变
.gradient {
  background: linear-gradient(180deg, rgba(31, 33, 35, 0) 70%, #94121d 100%);
}
</style>
